<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="closeDialog"
      width="600px"
    >
      <div class="brand-relation-container">
        <!-- 左侧选择区域 -->
        <div class="select-category">
          <el-button type="primary" plain @click="openDialog">新增关联</el-button>
        </div>

        <!-- 右侧已关联列表 -->
        <div class="relation-list">
          <div class="list-title">已关联分类</div>
          <div v-if="cateList.length > 0" class="cate-list">
            <el-table :data="cateList" style="width: 100%" size="small" border>
              <el-table-column
                prop="catelogId"
                label="分类ID"
                width="120"
                align="center"
              >
              </el-table-column>
              <el-table-column prop="catelogName" label="分类名称" align="center">
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope.row)"
                  >
                    解除关联
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="empty-text">暂无关联分类</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    </el-dialog>

    <!-- 弹窗 -->
    <el-dialog title="选择关联属性" :visible.sync="dialogVisible" @close="resetSelection">
      <el-table
        :data="attrList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column
          prop="attrId"
          label="属性ID"
        ></el-table-column>
        <el-table-column
          prop="attrName"
          label="属性名称"
        ></el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
      </span>
    </el-dialog>
  </div>


</template>

<script>
import attrgroup from './attrgroup.vue'

export default {
  data () {
    return {
      dialogVisible: false, // 控制弹窗的显示与隐藏
      attrList: [], // 存储请求返回的属性列表
      selectedAttrs: [], // 存储选中的属性
      title: '',
      props:
        {
          value: 'catId',
          label:
            'name',
          children:
            'children',
        },
      value: [],
      options:
        [],
      visible:
        false,
      cateList:
        [],
      brandId:
        null,
      categoryId: null,// 保存当前品牌ID
    }
  },
  methods: {
    // 打开弹窗
    openDialog () {
      this.dialogVisible = true
      this.fetchAttrList() // 请求属性列表
    },
    // 重置选中的属性
    resetSelection () {
      this.selectedAttrs = []
    },
    // 获取属性列表
    fetchAttrList () {
      this.$http({
        url: this.$http.adornUrl(`/gulimailproduct/attrgroup/list/not-relation/${this.categoryId}`),
        method: 'get',
      }).then(({data}) => {
        this.attrList = data.data
      })
    },
    // 处理选中项变化
    handleSelectionChange (val) {
      this.selectedAttrs = val
      // console.log(this.selectedAttrs)
    },
    // 确认选中的属性并提交
    confirmSelection () {
      console.log(this.selectedAttrs)
      console.log(this.brandId)
      this.$http({
        url: this.$http.adornUrl(`/gulimailproduct/attrgroup/save/relation/${this.brandId}`),
        method: 'post',
        data: this.$http.adornData(this.selectedAttrs, false)
      }).then(({data}) => {
        this.dialogVisible = false
        this.fetchCateList(this.brandId)
      })
    },
    closeDialog () {
      this.value = []
    },
    getMenus () {
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/category/list/tree'),
        method: 'get',
      }).then(({data}) => {
        this.options = data.data
      })
    },
    fetchCateList (id) {
      this.$http({
        url: this.$http.adornUrl(
          `/gulimailproduct/attrgroup/list/relation`
        ),
        method: 'post',
        params: this.$http.adornParams({'attrGroupId': id})
      }).then(({data}) => {
        console.log(data)
        this.cateList = data.data.map((item) => ({
          catelogId: item.attrId,
          catelogName: item.attrName,
        }))
      })
    },
    init (id, catlogId) {
      this.brandId = id
      this.categoryId = catlogId
      this.visible = true
      this.fetchCateList(id)
    },
    // 解除关联
    handleDelete (row) {
      this.$confirm(`是否解除与分类【${row.catelogName}】的关联？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let datas = [{
          'attrGroupId': this.brandId,
          'attrId': row.catelogId,
        }]
        this.$http({
          url: this.$http.adornUrl(
            '/gulimailproduct/attrgroup/delete/relation'
          ),
          method: 'post',
          data: this.$http.adornData(datas, false),
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('解除关联成功')
            this.fetchCateList(this.brandId)
          } else {
            console.log(data)
          }
        })
      })
    },
    // 表单提交
    dataFormSubmit () {
      // if (!this.value || this.value.length === 0) {
      //   this.$message.warning("请选择要关联的分类");
      //   return;
      // }

      // // 获取最后一级分类ID
      // const categoryId = this.value[this.value.length - 1];

      // this.$http({
      //   url: this.$http.adornUrl("/gulimailproduct/categorybrandrelation/save"),
      //   method: "post",
      //   data: this.$http.adornData({
      //     brandId: this.brandId,
      //     catelogId: categoryId,
      //   }),
      // }).then(({ data }) => {
      //   if (data && data.code === 0) {
      //     this.$message.success("关联成功");
      //     this.fetchCateList(this.brandId);
      //     this.value = []; // 清空选择
      //   } else {
      //     this.$message.error(data.msg || "关联失败");
      //   }
      // });
      this.visible = false
    },
  },
  created () {
    this.getMenus()
  },
}
</script>

<style scoped>
.brand-relation-container {
  padding: 20px;
}

.select-category {
  margin-bottom: 30px;
}

.select-title,
.list-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
  font-weight: bold;
}

.relation-list {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.cate-list {
  margin-top: 15px;
}

.empty-text {
  color: #909399;
  text-align: center;
  margin: 20px 0;
}

/* 级联选择器样式 */
.el-cascader {
  width: 100%;
}

/* 表格内按钮样式 */
.el-button--text {
  color: #ff4949;
}

.el-button--text:hover {
  color: #ff6d6d;
}
</style>
